package com.qimo.service.Impl;

import com.qimo.dao.ItemDao;
import com.qimo.dao.OrderDao;
import com.qimo.model.HistoryOrder;
import com.qimo.model.Order;
import com.qimo.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service("OrderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;
    @Resource
    private ItemDao itemDao;
    public int createOrder(Order order) {

        if(orderDao.createOrder(order)>0)
           return this.itemDao.BuyItem(order.getItemId(),order.getNumber());
           else return 0;
    }

    public List<Order> selectOrderList(Integer userId,Integer orderId,Integer Page) {
        return this.orderDao.selectOrderList(userId,null,(Page-1)*4);
    }


    public int selectOrderListCount(int userId) {
        return this.orderDao.selectOrderListCount(userId);
    }

    public boolean cancelOrder(int orderId, int userId) {
       Order temp=this.orderDao.selectOrderList(userId,orderId,0).get(0);
       if (null==temp) return false;
        if(temp.getStatus()==0)//订单状态为待发货可以取消
        {
            temp.setStatus(3);//历史订单状态为已退款
           if(this.orderDao.createHistoryOrder(temp)>0)//创建订单并删除历史订单
           {
               if(this.orderDao.delOrder(orderId, userId)>0)
                   if(this.itemDao.cancelItem(temp.getItemId(),temp.getNumber())>0)
                        return true;
                   else return false;
                   else return false;
           }
           else return false;
        }
        else return false;
    }

    public boolean completeOrder(int orderId, int userId) {
        Order temp=this.orderDao.selectOrderList(userId,orderId,0).get(0);
        if (null==temp) return false;
        if(temp.getStatus()==1)//订单状态为已发货可以确认收货
        {
            temp.setStatus(2);//正常完成订单
            if(this.orderDao.createHistoryOrder(temp)>0)//创建订单并删除历史订单
            {
                this.orderDao.delOrder(orderId, userId);
                return true;
            }
            else return false;
        }
        else return false;
    }

    public List<HistoryOrder> selectHistoryOrderList(Integer userId,Integer Page) {

        return this.orderDao.selectHistoryOrderList(userId,(Page-1)*4);
    }

    public int selectHistoryOrderListCount(int userId) {
        return this.orderDao.selectHistoryOrderListCount(userId);
    }

    public int delHistoryOrder(int historyOrderId, int userId) {
        return this.orderDao.delHistoryOrder(historyOrderId,userId);
    }

}
